/*
 */

package com.railway.msg.action;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import cn.org.rapid_framework.page.Page;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.railway.common.base.BaseStruts2Action;
import com.railway.common.constants.SysConstant;
import com.railway.common.util.Json;
import com.railway.common.util.StaticMethod;
import com.railway.msg.constants.IConstant;
import com.railway.msg.model.MsgSend;
import com.railway.msg.service.IMsgSendManager;
import com.railway.msg.vo.query.MsgSendQuery;
import com.railway.system.model.SysDept;
import com.railway.system.model.SysUser;
import com.railway.system.service.ISysDeptManager;
import com.railway.system.service.ISysUserManager;
import com.railway.system.vo.query.SysUserQuery;

/**
 * @author  jiangcheng
 * @version 1.0
 * @since 1.0
 */

public class MsgSendAction extends BaseStruts2Action implements Preparable,
		ModelDriven {
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;
	private ISysUserManager sysUserManager;
	//forward paths
	protected static final String QUERY_JSP = "/admin/msg/msgSend/query.jsp";
	protected static final String LIST_JSP = "/admin/msg/msgSend/list.jsp";
	protected static final String CREATE_JSP = "/admin/msg/msgSend/create.jsp";
	protected static final String EDIT_JSP = "/admin/msg/msgSend/edit.jsp";
	protected static final String SHOW_JSP = "/admin/msg/msgSend/show.jsp";
	//redirect paths,startWith: !
	protected static final String LIST_ACTION = "!/msg/MsgSend/list.do";

	private ISysDeptManager sysDeptManager;
	private IMsgSendManager msgSendManager;
	public void setSysUserManager(ISysUserManager manager) {
		this.sysUserManager = manager;
	}
	public void setSysDeptManager(ISysDeptManager sysDeptManager) {
		this.sysDeptManager = sysDeptManager;
	}

	private MsgSend msgSend;
	java.lang.String id = null;
	private String[] items;
	private String param;

	public void setParam(String param) {
		this.param = param;
	}

	public void prepare() throws Exception {
		if (isNullOrEmptyString(id)) {
			msgSend = new MsgSend();
		} else {
			msgSend = (MsgSend) msgSendManager.getById(id);
		}
	}

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,注意大小写 */
	public void setMsgSendManager(IMsgSendManager manager) {
		this.msgSendManager = manager;
	}

	public Object getModel() {
		return msgSend;
	}

	public void setId(java.lang.String val) {
		this.id = val;
	}

	public void setItems(String[] items) {
		this.items = items;
	}

	/** 执行搜索 */
	public String list() {
		return LIST_JSP;
	}





	public String listAjax() {

		MsgSendQuery query = newQuery(MsgSendQuery.class, DEFAULT_SORT_COLUMNS);
		String current_user_id = (String)this.getRequest().getSession().getAttribute("userId");
		query.setCreator(current_user_id == null?SysConstant.SYS_EMPTY_VALUE:current_user_id);
		query.setTitles(IConstant.MSG_STATUS_NORMAL);
		query.setSortColumns(" create_Time DESC");
		Page page = msgSendManager.findPage(query);
		Map map = new HashMap();
		map.put("total", page.getTotalCount());
		map.put("rows", page.getResult());
		return writeAjaxResponse(Json.toJson(map));
	}

	/** 查看对象*/
	public String show() {
		return SHOW_JSP;
	}

	/** 进入新增页面*/
	public String create() {
		//取得联合查询的结果放入session
//		long t = System.currentTimeMillis();
		
		String calltypes1 = this.getRequest().getParameter(SysConstant.USER_CALL_TYPES);
		
		
		// 获得在线用户
//		ServletContext application = this.getRequest().getSession().getServletContext();
//		Set sessions = (HashSet) application.getAttribute(SysConstant.USER_SESSIONS);
//		Map umap = new HashMap();
//		if (sessions != null) {
//			for (Iterator it = sessions.iterator(); it.hasNext();) {				
//				HttpSession sess = (HttpSession) it.next();
//				umap.put((String) sess.getAttribute(SysConstant.USER_ID), "");
//			}
//		}

		
		
		
//		StringBuffer resultsb = new StringBuffer();
		
//		resultsb.append("[");
		// 获得所有部门
		
		List<SysDept> deptList = sysDeptManager.findAll();
		
		if (deptList != null) {
			
			SysDept temp_sd = new SysDept();
			temp_sd.setId("EMPTY");//部门为空的情况
			temp_sd.setDeptName("");
			
			deptList.add(temp_sd);

			for (int i = 0; i < deptList.size(); i++) {
			
				SysDept sd = (SysDept) deptList.get(i);
 
//				if (i > 0) {
//					resultsb.append(",");
//				}
//				resultsb.append("{dn:\"").append(sd.getDeptName()).append("\",did:\"").append(
//						sd.getId() == "" ? System.currentTimeMillis() + i : sd
//								.getId());
//				resultsb.append("\",users:[");

				// 根据部门获得相应的用户列表
				SysUserQuery query = newQuery(SysUserQuery.class,DEFAULT_SORT_COLUMNS);				
					query.setDeptId(sd.getId());
					query.setSortColumns("USER_NO");
				    
				    List userList = sysUserManager.getUsers(query);
				    sd.setUserlist(userList);

//				    if (userList != null) {
//				    	for (int k = 0; k < userList.size(); k++) {
//
//				    		SysUser su = (SysUser) userList.get(k);
//				    		//
//				    		//判断一下,如果是消息呼叫用户列表则不显示虚拟用户
//				    		
//						// 如果是部门虚拟用户,则退出
//				    		if(SysConstant.USER_CALL_TYPES_MSG.equals(calltypes)){
//				    		  if ((SysConstant.ID_TYPE_DEPT).equals(su.getCardType())){
//				    			continue;
//				    		  }
//				    		}
//				    		if (k > 0) {
//				    			resultsb.append(",");
//				    		}
//
//						StringBuffer b = new StringBuffer();
//						b.append("姓名:").append(
//								StaticMethod.null2String(su.getUserName()));
//						b
//								.append("<br>职务:")
//								.append(
//										StaticMethod.null2String(su
//												.getPosition()))
//								.append("<br>电话:")
//								.append(StaticMethod.null2String(su.getPhone()))
//								.append("<br>手机:").append(
//										StaticMethod
//												.null2String(su.getMobile()));
//
//						resultsb.append("{un:\"").append(su.getUserName())
//						.append("\",uid:\"").append(su.getId()).append(
//								"\",uinfo:\"").append(b.toString())
//						.append("\",ustatus:\"").append(
//								umap.get(su.getId()) == null ? "black"
//										: "blue").append("\"}");
//						
//
//					}
				}
		//	}
//				resultsb.append("]}");

			}

//		}
	

	
//		resultsb.append("]");


		
		HttpSession ssion= this.getRequest().getSession();
		
		if(ssion.getAttribute("DEPT_USER_LINK_LIST") == null){
			ssion.setAttribute("DEPT_USER_LINK_LIST", deptList);
		}
 
		
		return CREATE_JSP;
	}

	/** 保存新增对象 */
	public String save() {
//		String savePath = ServletActionContext.getServletContext().getRealPath(
//		""); //获取项目根路径 
//savePath = savePath + "/newscontent/";	
 
//		System.out.println("保存一个消息.... .. ... . . .. ");
		String current_user_id = (String)this.getRequest().getSession().getAttribute("userId");
		msgSend.setCreator(current_user_id);
		msgSend.setTitles(IConstant.MSG_STATUS_NORMAL);
		msgSendManager.save(msgSend);
		return LIST_ACTION;
	}

	/**进入更新页面*/
	public String edit() {
		return EDIT_JSP;
	}

	/**保存更新对象*/
	public String update() {
		msgSendManager.update(this.msgSend);
		return LIST_ACTION;
	}

	/**删除对象*/
	public String delete() {
		try{if (items != null)
			for (String ids : items) {
				String[] idArray = ids.split(",");
				for (String id : idArray){
					//这里是更新状态
				    MsgSend ms = 	msgSendManager.getById(id);
				    ms.setTitles(IConstant.MSG_STATUS_DELETED);
					msgSendManager.update(ms);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return LIST_ACTION;
	}

}
